const Koa = require("koa");
const bodyParser = require("koa-bodyparser");
const cors = require("@koa/cors");
const Router = require("koa-router");
const serve = require('koa-static');  // 添加这行
const path = require('path');         // 添加这行
const config = require("./config/base");
const initializeDatabase = require("./init.js");
const imageRouter = require('./routes/image');

const app = new Koa();
const router = new Router();

// 错误处理中间件
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    console.error("服务器错误:", err);
    ctx.status = err.status || 500;
    ctx.body = {
      error: err.message || "服务器错误",
    };
  }
});

// 中间件
app.use(cors());
app.use(bodyParser());

// 添加静态文件服务
app.use(serve(path.join(__dirname, 'public')));

// 基础路由
router.get("/", async (ctx) => {
  ctx.body = { message: "API 服务器运行正常" };
});

// 先注册不需要验证的路由
const authRoutes = require("./routes/auth");
app.use(authRoutes.routes());
app.use(authRoutes.allowedMethods());

// 再注册需要验证的路由
const chatRoutes = require("./routes/chat");
const userRoutes = require("./routes/user");

app.use(chatRoutes.routes());
app.use(chatRoutes.allowedMethods());
app.use(userRoutes.routes());
app.use(userRoutes.allowedMethods());

// 注册图像路由
app.use(imageRouter.routes());
app.use(imageRouter.allowedMethods());

// 导入反馈路由
const feedbackRouter = require('./routes/feedback');

// 注册反馈路由
app.use(feedbackRouter.routes());
app.use(feedbackRouter.allowedMethods());

// 启动服务器
const PORT = config.port || 3000;

app.listen(PORT, async () => {
  try {
    console.log(`服务器启动在 http://localhost:${PORT}`);
    await initializeDatabase();
    console.log('服务器初始化完成');
  } catch (error) {
    console.error("服务器启动失败:", error);
    process.exit(1);
  }
});

module.exports = app;
